﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using IRC.NET.Net;
using IRC.NET.Commands;
using System.Configuration;
using IRC.NET.Users;
using System.IO;

namespace IRC.NET
{
    public partial class Form1 : Form
    {
        private IrcServer _server;
        private delegate void TextBoxUpdatedDelegate(string message);
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string username = ConfigurationManager.AppSettings["TestUsername"].ToString();
            string nickname = ConfigurationManager.AppSettings["TestNickname"].ToString();
            string realname = ConfigurationManager.AppSettings["TestRealName"].ToString();

            ClientUser user = new ClientUser(username, nickname, realname);
            this._server = new IrcServer(this.textBox1.Text, user);
            this._server.AuthNoticeRecieved += new MessageEventHandler(_AuthNoticeMessageRecieved);
            this._server.UnknownMessageRecieved += new MessageEventHandler(_UnknownMessageRecieved);
            this._server.Authenticated += new ServerEventHandler(_Authenticated);
            this._server.ConnectionOpened += new ServerEventHandler(_ConnectionOpened);
            this._server.JoinedChannel += new ChannelEventHandler(_ChannelJoined);
            this._server.Open();
            
            //IrcContext.Current.User = user;

            //this._connection.OpenConnection();
            ////this._connection.SendCommand(new PassCommand(user));
            //this._connection.SendCommand(new NickCommand(user));
            //this._connection.SendCommand(new UserCommand(user));
        }

        private void _ConnectionOpened(object sender, IrcServerEventArgs args)
        {
            string message = "Prefix connection opened." + Environment.NewLine;
            this.textBox2.Invoke(new TextBoxUpdatedDelegate(textBox2_InvokeMessageRecieved), new object[] { message });
        }

        private void _ChannelJoined(object sender, ChannelEventArgs args)
        {
            string message = "A channel has been joined.." + Environment.NewLine;
            this.textBox2.Invoke(new TextBoxUpdatedDelegate(textBox2_InvokeMessageRecieved), new object[] { message });
        }

        private void _Authenticated(object sender, IrcServerEventArgs args)
        {
            string message = "Authenticated with server." + Environment.NewLine;
            this.textBox2.Invoke(new TextBoxUpdatedDelegate(textBox2_InvokeMessageRecieved), new object[] { message });

            if (sender is IrcServer)
            {
                // Set the form name to IRC server.
                this.Invoke(new TextBoxUpdatedDelegate(Form1_SetTitle), new object[] { ((IrcServer)sender).Host });
            }
        }

        private void _UnknownMessageRecieved(object sender, IrcServerMessageEventArgs args)
        {
            string message = args.Message + Environment.NewLine;
            this.textBox2.Invoke(new TextBoxUpdatedDelegate(textBox2_InvokeMessageRecieved), new object[] { message });
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.textBox1.Text = ConfigurationManager.AppSettings["TestServer"].ToString();
        }

        private void Form1_SetTitle(string message)
        {
            this.Text = message;
        }

        private void IrcServerConnection_MessageRecieved(object sender, MessageRecievedEventArgs args)
        {
            string message = (args.Message + Environment.NewLine);
            this.textBox2.Invoke(new TextBoxUpdatedDelegate(textBox2_InvokeMessageRecieved), new object[] { message });
        }

        private void _AuthNoticeMessageRecieved(object sender, IrcServerMessageEventArgs args)
        {
            string message = (args.Message + Environment.NewLine);
            this.textBox2.Invoke(new TextBoxUpdatedDelegate(textBox2_InvokeMessageRecieved), new object[] { message });
        }

        private void textBox2_InvokeMessageRecieved(string message)
        {
            this.textBox2.Text += message;
			this.textBox2.ScrollToCaret();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        protected override void OnClosing(CancelEventArgs e)
        {
            base.OnClosing(e);

            // Close our connection.
            if (this._server != null)
            {
                this._server.Close();
            }
        }

        private void textBox3_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
        {
            
        }

        private void textBox3_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar != '\r')
            {
                return;
            }
            e.Handled = true;

            string command = this.textBox3.Text;

            if (string.IsNullOrEmpty(command))
            {
                return;
            }

            int idx = command.IndexOf(" ");
            if (idx < 0)
            {
                // This is a chat message I think.
                this.textBox3.Text = string.Empty;
                return;
            }
            
            string opcode = command.Substring(0, idx);
            if ("JOIN".Equals(opcode.ToUpper()))
            {
                idx++;
                string channel = command.Substring(idx, command.Length-idx);
                this._server.JoinChannel(channel);
            }
            else if ("PART".Equals(opcode.ToUpper()))
            {
                idx++;
                string channel = command.Substring(idx, command.Length-idx);
                this._server.LeaveChannel(channel);
            }
            this.textBox3.Text = string.Empty;
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "Log Files|*.log";
            save.DefaultExt = "log";

            DialogResult result = save.ShowDialog();
            if (result == DialogResult.OK)
            {
                string text = this.textBox2.Text;
                File.WriteAllText(save.FileName, text);
            }
        }
    }
}
